package cn.ddiancan.xddcloud.common.endpoints;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class XddcloudInfoContributor implements InfoContributor {

    @Override
    public void contribute(Info.Builder builder) {
        // 1. 添加当前日期（发布日期）
        builder.withDetail("current.date", LocalDateTime.now());

        // 2. 添加 Maven 信息（如版本号）
        builder.withDetails(getMavenInfo());
    }

    private Map<String, Object> getMavenInfo() {
        String mavenPropertiesPath = "META-INF/MANIFEST.MF";
        Properties properties = new Properties();
        try {
            properties.load(XddcloudInfoContributor.class.getClassLoader().getResourceAsStream(mavenPropertiesPath));
            return properties.stringPropertyNames().stream()
                .collect(Collectors.toMap(k -> k, properties::getProperty));
        } catch (IOException e) {
            log.error("Error during reading maven properties: {}", e.getMessage());
        }
        return Collections.emptyMap();
    }
}
